/*
 * max31865.c
 *
 *  Created on: 2021年5月22日
 *      Author: Rupert
 */
#include "MAX31865.h"

#include "main.h"
#include "stm32f4xx_ll_gpio.h"
#include "math.h"

#define MAX31865_CS_SET LL_GPIO_SetOutputPin(MAX_SPI_CS_GPIO_Port, MAX_SPI_CS_Pin)
#define MAX31865_CS_CLR LL_GPIO_ResetOutputPin(MAX_SPI_CS_GPIO_Port, MAX_SPI_CS_Pin)
#define MAX31865_SCLK_SET LL_GPIO_SetOutputPin(MAX_SPI_SCK_GPIO_Port, MAX_SPI_SCK_Pin)
#define MAX31865_SCLK_CLR LL_GPIO_ResetOutputPin(MAX_SPI_SCK_GPIO_Port, MAX_SPI_SCK_Pin)
#define MAX31865_SDI_SET LL_GPIO_SetOutputPin(MAX_SPI_MOSI_GPIO_Port, MAX_SPI_MOSI_Pin)
#define MAX31865_SDI_CLR LL_GPIO_ResetOutputPin(MAX_SPI_MOSI_GPIO_Port, MAX_SPI_MOSI_Pin)

#define MAX31865_SDO_READ LL_GPIO_IsInputPinSet(MAX_SPI_MISO_GPIO_Port, MAX_SPI_MISO_Pin)

static void MAX31865_WriteData(uint8_t addr, uint8_t data)
{

	unsigned char i;

	MAX31865_CS_CLR;
	for(i=0;i<8;i++)  //写地址
	{
		MAX31865_SCLK_CLR;
		if(addr&0x80) MAX31865_SDI_SET;
		else MAX31865_SDI_CLR;
		MAX31865_SCLK_SET;
		addr<<=1;
	}
	for(i=0;i<8;i++)  //写数据
	{
		MAX31865_SCLK_CLR;
		if(data&0x80) MAX31865_SDI_SET;
		else MAX31865_SDI_CLR;
		MAX31865_SCLK_SET;
		data<<=1;
	}
	MAX31865_CS_SET;
}

static uint8_t MAX31865_ReadData(uint8_t addr)
{
	unsigned char i;
	unsigned char data=0;

	MAX31865_CS_CLR;
	for(i=0;i<8;i++)  //写地址
	{
		MAX31865_SCLK_CLR;
		if(addr&0x80) MAX31865_SDI_SET;
		else MAX31865_SDI_CLR;
		MAX31865_SCLK_SET;
		addr<<=1;
	}
	for(i=0;i<8;i++)  //读数据
	{
		MAX31865_SCLK_CLR;
		data<<=1;
		MAX31865_SCLK_SET;
		if(MAX31865_SDO_READ) data|=0x01;
		else data|=0x00;
	}
	MAX31865_CS_SET;
	return data;
}

float MAX31865_GetTemp()
{
	uint16_t data;
	float Rt;
	float Rt0 = 100; // PT100
	float Z1, Z2, Z3, Z4, temp;
	float a = 3.9083e-3;
	float b = -5.775e-7;
	float rpoly;

	//MAX31865_Write(0x80, 0xD3);
	data = MAX31865_ReadData(0x01) << 8;
	data |= MAX31865_ReadData(0x02);
	data >>= 1;  // 去掉 Fault 位
	Rt = (float) (data - 2) / 32768.0 * RREF;

	Z1 = -a;
	Z2 = a * a - 4 * b;
	Z3 = 4 * b / Rt0;
	Z4 = 2 * b;

	temp = Z2 + Z3 * Rt;
	temp = (sqrt(temp) + Z1) / Z4;

	if (temp >= 0)
		return temp;

	rpoly = Rt;
	temp = -242.02;
	temp += 2.2228 * rpoly;
	rpoly *= Rt;  // square
	temp += 2.5859e-3 * rpoly;
	rpoly *= Rt;  // ^3
	temp -= 4.8260e-6 * rpoly;
	rpoly *= Rt;  // ^4
	temp -= 2.8183e-8 * rpoly;
	rpoly *= Rt;  // ^5
	temp += 1.5243e-10 * rpoly;

	return temp;
}

void MAX31865_Config(void)
{
	MAX31865_WriteData(0x80, 0xD3); //BIAS ON, 自动，4线，50HZ  根据文件修改四线还是三线   1101
}
